<template>
  <div class="p-2 page-flex">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目名称" prop="proName">
              <el-input v-model="queryParams.proName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="执行总裁" prop="proPresidentId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择执行总裁" style="width: 240px" clearable @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="proLeaderId">
              <el-select
                :model-value="selectedSearchLeader ? selectedSearchLeader.userName || selectedSearchLeader.nickName : ''"
                placeholder="请选择项目负责人" style="width: 240px" clearable @click="showSearchLeaderSelector = true"
                @clear="clearSearchLeader">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchLeaderSelector = true"> 选择项目负责人 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['project:proQualityExternalaud:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['project:proQualityExternalaud:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['project:proQualityExternalaud:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['project:proQualityExternalaud:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="proQualityExternalaudList" @selection-change="handleSelectionChange" border class="flex-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="填报人" align="center" prop="recordName" width="150" />
        <el-table-column label="填报日期" align="center" prop="recordTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="proName" :show-overflow-tooltip="true" />
        <el-table-column label="输出方式" align="center" prop="exportWay" width="120">
          <template #default="scope">
            <dict-tag :options="pro_export_way" :value="scope.row.exportWay" />
          </template>
        </el-table-column>
        <el-table-column label="输出人" align="center" prop="exportName" :show-overflow-tooltip="true" />
        <el-table-column label="接受单位" align="center" prop="receiveUnit" />
        <el-table-column label="接收人" align="center" prop="receiveBy" :show-overflow-tooltip="true" />
        <el-table-column label="对外输出资料清单" align="center" prop="exportData" :show-overflow-tooltip="true" />
        <el-table-column label="公司审核状态" align="center" prop="companyAuditStatus" width="120">
          <template #default="scope">
            <dict-tag :options="pro_quality_is_approval" :value="scope.row.companyAuditStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['project:proQualityExternalaud:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['project:proQualityExternalaud:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination class="pagination-fixed" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改项目成果对外输出审批对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <div style="padding: 20px 0 20px 24px; padding-right: 24px">
        <el-form ref="proQualityExternalaudFormRef" :model="form" :rules="rules" label-width="140px"
          label-position="left" style="width: 100%">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="填报日期" prop="recordTime">
                <el-date-picker v-model="form.recordTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择填报日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="填报人" prop="recordBy">
                <el-input :value="form.recordName || userStore.name" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目名称" prop="proId">
                <el-select v-model="form.proId" placeholder="请输入项目名称搜索" clearable filterable remote reserve-keyword
                  :remote-method="searchProjects" :loading="projectLoading" style="width: 100%"
                  @change="handleProjectChange">
                  <el-option v-for="project in projectList" :key="project.id"
                    :label="`${project.proName} (${project.proNumber || ''})`" :value="project.id" />
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="projectSearchKeyword && projectList.length === 0"> 未找到相关项目 </span>
                      <span v-else> 请输入项目名称进行搜索 </span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目执行总裁" prop="proPresidentsName">
                <el-input v-model="form.proPresidentsName" readonly placeholder="请选择项目" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目负责人" prop="proLeadersName">
                <el-input v-model="form.proLeadersName" readonly placeholder="请选择项目" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="对外输出资料清单" prop="exportData">
                <el-input v-model="form.exportData" type="textarea" :rows="4" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否通过公司审核">
                <dict-tag :options="pro_quality_is_approval" :value="auditStatus.company.isApproval" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="输出方式" prop="exportWay">
                <el-select v-model="form.exportWay" placeholder="请选择输出方式" style="width: 100%">
                  <el-option v-for="dict in pro_export_way" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="输出人" prop="exportBy">
                <div class="user-selector-container">
                  <div class="selected-users" v-if="selectedExportBy.length > 0" style="margin-bottom: 8px">
                    <el-tag v-for="user in selectedExportBy" :key="user.userId" closable @close="removeExportBy(user)"
                      type="primary" style="margin-right: 8px; margin-bottom: 4px">
                      {{ user.userName || user.nickName }}
                    </el-tag>
                  </div>
                  <el-button type="primary" plain @click="showExportBySelector = true" style="width: 100%">
                    {{ selectedExportBy.length > 0 ? '重新选择输出人' : '选择输出人' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="接受单位" prop="receiveUnit">
                <el-input v-model="form.receiveUnit" placeholder="请输入接受单位" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="接收人" prop="receiveBy">
                <el-input v-model="form.receiveBy" placeholder="请输入接收人" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 输出人选择器 -->
    <UserSelector v-model:visible="showExportBySelector" title="选择输出人" :selected-user-names="form.exportBy || ''"
      :multiple="true" @confirmWithIds="handleExportByConfirmWithIds" @cancel="handleExportBySelectorCancel" />

    <!-- 搜索用执行总裁选择器 -->
    <UserSelector v-model:visible="showSearchPresidentSelector" title="选择执行总裁"
      :selected-user-names="queryParams.proPresidentId || ''" :multiple="false"
      @confirmWithIds="handleSearchPresidentConfirm" @cancel="handleSearchPresidentCancel" />

    <!-- 搜索用项目负责人选择器 -->
    <UserSelector v-model:visible="showSearchLeaderSelector" title="选择项目负责人"
      :selected-user-names="queryParams.proLeaderId || ''" :multiple="false" @confirmWithIds="handleSearchLeaderConfirm"
      @cancel="handleSearchLeaderCancel" />
  </div>
</template>

<script setup name="ProQualityExternalaud" lang="ts">
import {
  listProQualityExternalaud,
  getProQualityExternalaud,
  delProQualityExternalaud,
  addProQualityExternalaud,
  updateProQualityExternalaud,
  fetchAuditRecordByProId
} from '@/api/project/quality';
import { ProQualityExternalaudVO, ProQualityExternalaudQuery, ProQualityExternalaudForm } from '@/api/project/quality/types';
import { listProInfoForQuery } from '@/api/project/init/proInfo';
import { useUserStore } from '@/store/modules/user';
import { getToday } from '@/utils/dateUtils';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pro_quality_is_approval, pro_export_way } = toRefs<any>(proxy?.useDict('pro_quality_is_approval', 'pro_export_way'));

const proQualityExternalaudList = ref<ProQualityExternalaudVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const proQualityExternalaudFormRef = ref<ElFormInstance>();

// 输出人选择相关状态
const showExportBySelector = ref(false);
const selectedExportBy = ref<any[]>([]);

// 搜索用执行总裁选择相关状态
const showSearchPresidentSelector = ref(false);
const selectedSearchPresident = ref<any>(null);

// 搜索用项目负责人选择相关状态
const showSearchLeaderSelector = ref(false);
const selectedSearchLeader = ref<any>(null);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const userStore = useUserStore();

// 审核通过字典映射
const approvalMap = { '0': '未审查', '1': '通过', '2': '不通过', undefined: '未审查', null: '未审查', '': '未审查' };
const approvalColorMap = { '0': 'info', '1': 'success', '2': 'danger', undefined: 'info', null: 'info', '': 'info' };
const auditStatus = reactive({
  company: { isApproval: undefined, id: undefined }
});

const initFormData: ProQualityExternalaudForm = {
  id: undefined,
  recordBy: undefined,
  recordName: '',
  recordTime: undefined,
  proId: undefined,
  proName: '',
  proPresidentsName: '',
  proLeadersName: '',
  exportWay: undefined,
  exportBy: undefined,
  receiveUnit: undefined,
  receiveBy: undefined,
  exportData: undefined,
  remark: undefined,
  exportName: '',
  companyAuditId: undefined
};

const data = reactive<PageData<ProQualityExternalaudForm, ProQualityExternalaudQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    proName: undefined,
    proPresidentId: undefined,
    proLeaderId: undefined,
    params: {}
  },
  rules: {
    recordBy: [{ required: true, message: '填报人不能为空', trigger: 'blur' }],
    recordTime: [{ required: true, message: '填报日期不能为空', trigger: 'blur' }],
    proId: [{ required: true, message: '项目名称不能为空', trigger: 'change' }],
    proPresidentsName: [{ required: true, message: '项目执行总裁不能为空', trigger: 'change' }],
    proLeadersName: [{ required: true, message: '项目负责人不能为空', trigger: 'change' }],
    exportWay: [{ required: true, message: '输出方式不能为空', trigger: 'blur' }],
    exportBy: [{ required: true, message: '输出人不能为空', trigger: 'blur' }],
    receiveUnit: [{ required: true, message: '接受单位不能为空', trigger: 'blur' }],
    exportData: [{ required: true, message: '对外输出资料清单不能为空', trigger: 'blur' }],
    companyAuditId: [{ required: true, message: '公司审核ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const projectList = ref<any[]>([]);
const projectLoading = ref(false);
const projectSearchKeyword = ref('');

const searchProjects = (query: string) => {
  projectSearchKeyword.value = query;
  if (searchProjects.timer) clearTimeout(searchProjects.timer);
  searchProjects.timer = setTimeout(() => {
    getProjectList(query);
  }, 300);
};
searchProjects.timer = null;

const getProjectList = async (searchKeyword = '') => {
  try {
    projectLoading.value = true;
    const res = await listProInfoForQuery({ pageNum: 1, pageSize: 50, proName: searchKeyword || undefined, auditStatus: '3' });
    projectList.value = res.rows || [];
  } finally {
    projectLoading.value = false;
  }
};

/** 查询项目成果对外输出审批列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProQualityExternalaud(queryParams.value);
  proQualityExternalaudList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };

  // 清除人员选择状态
  selectedExportBy.value = [];
  showExportBySelector.value = false;

  // 清除审核状态
  auditStatus.company.isApproval = undefined;
  auditStatus.company.id = undefined;

  // 清除项目列表和搜索状态
  projectList.value = [];
  projectSearchKeyword.value = '';
  projectLoading.value = false;

  proQualityExternalaudFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.proName = undefined;
  queryParams.value.proPresidentId = undefined;
  queryParams.value.proLeaderId = undefined;
  selectedSearchPresident.value = null;
  selectedSearchLeader.value = null;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProQualityExternalaudVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.recordTime = getToday();
  form.value.recordBy = Number(userStore.userId);
  dialog.visible = true;
  dialog.title = '添加项目成果对外输出审批';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProQualityExternalaudVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getProQualityExternalaud(_id);
  Object.assign(form.value, res.data);

  // 回显审核状态
  auditStatus.company.isApproval = res.data.companyAuditStatus;

  // 回显exportName和
  form.value.exportName = res.data.exportName || '';

  // 项目回显，参照auditRecord页面
  if (form.value.proId) {
    try {
      const projectRes = await listProInfoForQuery({ id: form.value.proId, pageNum: 1, pageSize: 1, auditStatus: '3' });
      const projectArr = Array.isArray(projectRes.rows) ? projectRes.rows : [];
      if (projectArr.length > 0) {
        const project = projectArr[0];
        if (!projectList.value.find((p) => p.id === project.id)) {
          projectList.value.unshift({
            id: project.id,
            proName: project.proName,
            proNumber: project.proNumber,
            proPresidentsName: project.proPresidentsName,
            proLeadersName: project.proLeadersName
          });
        }
        // 回显执行总裁和项目负责人
        form.value.proPresidentsName = project.proPresidentsName || '';
        form.value.proLeadersName = project.proLeadersName || '';
      }
    } catch (e) {
      // ignore
    }
  }

  // 初始化输出人选择状态
  initExportByFromForm();
  dialog.visible = true;
  dialog.title = '修改项目成果对外输出审批';
};

/** 提交按钮 */
const submitForm = () => {
  proQualityExternalaudFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateProQualityExternalaud(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProQualityExternalaud(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProQualityExternalaudVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目成果对外输出审批编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delProQualityExternalaud(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'pro/quality/externalAudit/export',
    {
      ...queryParams.value
    },
    `project_quality_externalaud_${new Date().getTime()}.xlsx`
  );
};

// 选中项目后自动回显执行总裁和负责人
const handleProjectChange = async (proId: string | number) => {
  if (!proId) {
    form.value.proPresidentsName = '';
    form.value.proLeadersName = '';
    return;
  }
  const project = projectList.value.find((p) => p.id === proId);
  if (project) {
    form.value.proPresidentsName = project.proPresidentsName || '';
    form.value.proLeadersName = project.proLeadersName || '';
  } else {
    form.value.proPresidentsName = '';
    form.value.proLeadersName = '';
  }
  // 查询项目的公司审核记录
  const res = await fetchAuditRecordByProId(proId);
  const companyAuditRecord = res?.data;
  // 赋值公司审核
  if (companyAuditRecord) {
    auditStatus.company.isApproval = companyAuditRecord.isApproval;
    form.value.companyAuditId = companyAuditRecord.id;
  } else {
    auditStatus.company.isApproval = undefined;
    form.value.companyAuditId = undefined;
  }
};

// 输出人选择相关方法
const initExportByFromForm = () => {
  if (form.value.exportBy) {
    const ids = form.value.exportBy
      .split(',')
      .map((id) => id.trim())
      .filter((id) => id);
    const names = form.value.exportName
      ? form.value.exportName
        .split(',')
        .map((name) => name.trim())
        .filter((name) => name)
      : [];
    selectedExportBy.value = ids.map((id, index) => ({
      userId: id,
      userName: names[index] || `用户${index + 1}`,
      nickName: names[index] || `用户${index + 1}`,
      deptName: '未分配部门'
    }));
  } else {
    selectedExportBy.value = [];
  }
};

const handleExportByConfirmWithIds = (data: { users: any[]; userIds: string; userNames: string }) => {
  selectedExportBy.value = data.users;
  form.value.exportBy = data.userIds;
  showExportBySelector.value = false;
};

const handleExportBySelectorCancel = () => {
  showExportBySelector.value = false;
};

const removeExportBy = (user: any) => {
  const index = selectedExportBy.value.findIndex((u) => u.userId === user.userId);
  if (index > -1) {
    selectedExportBy.value.splice(index, 1);
    // 更新表单字段
    form.value.exportBy = selectedExportBy.value.map((u) => u.userId).join(',');
  }
};

// 搜索用执行总裁选择器相关方法
const handleSearchPresidentConfirm = (data: any) => {
  selectedSearchPresident.value = data.users && data.users.length > 0 ? data.users[0] : null;
  queryParams.value.proPresidentId = data.userIds;
  showSearchPresidentSelector.value = false;
};

const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  queryParams.value.proPresidentId = undefined;
};

// 搜索用项目负责人选择器相关方法
const handleSearchLeaderConfirm = (data: any) => {
  selectedSearchLeader.value = data.users && data.users.length > 0 ? data.users[0] : null;
  queryParams.value.proLeaderId = data.userIds;
  showSearchLeaderSelector.value = false;
};

const handleSearchLeaderCancel = () => {
  showSearchLeaderSelector.value = false;
};

const clearSearchLeader = () => {
  selectedSearchLeader.value = null;
  queryParams.value.proLeaderId = undefined;
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.user-selector-container {
  width: 100%;
}

.selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 页面弹性布局 */
.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

.pagination-fixed {
  margin-top: 8px;
}
</style>
